package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.Orderservice;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderserviceImpl implements Orderservice {
	
	@Value("${sky.shop.address}")
	private String shopAddress;
	@Value("${sky.baidu.ak}")
	private String ak;
	@Autowired
	private OrderMapper orderMapper;
	@Autowired
	private AddressBookMapper addressBookMapper;
	@Autowired
	private OrderDetailMapper orderDetailMapper;
	@Autowired
	private ShoppingCartMapper shoppingCartMapper;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private WeChatPayUtil weChatPayUtil;
	@Autowired
	private WebSocketServer webSocketServer;
	
	/**
	 * 查询订单
	 *
	 * @param id
	 * @return
	 */
	@Override
	public OrderVO getOrder(Long id) {
		// 根据id查询订单
		Orders orders = orderMapper.getOrder(id);
		// 查询该订单对应的菜品/套餐明细
		List<OrderDetail> orderDetailList = orderDetailMapper.getOrderId(orders.getId());
		// 将该订单及其详情封装到OrderVO并返回
		OrderVO orderVO = new OrderVO();
		BeanUtils.copyProperties(orders, orderVO);
		orderVO.setOrderDetailList(orderDetailList);
		
		return orderVO;
	}
	
	@Override
	@Transactional
	public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
		// 判断下单地址是否存在
		AddressBook address =
				addressBookMapper.getAddress(AddressBook.builder().id(ordersSubmitDTO.getAddressBookId()).build()).get(0);
		if (address == null) {
			throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
		}
		checkOutOfRange(address.getCityName() + address.getDistrictName() + address.getDetail());
		// 判断购物车数据
		List<ShoppingCart> cart =
				shoppingCartMapper.getCart(ShoppingCart.builder().userId(BaseContext.getCurrentId()).build());
		if (cart == null || cart.isEmpty()) {
			throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
		}
		// 下单
		Orders orders = new Orders();
		BeanUtils.copyProperties(ordersSubmitDTO, orders);
		orders.setPhone(address.getPhone());
		orders.setAddress(address.getDetail());
		orders.setConsignee(address.getConsignee());
		orders.setNumber(String.valueOf(System.currentTimeMillis()));
		orders.setUserId(BaseContext.getCurrentId());
		orders.setStatus(Orders.PENDING_PAYMENT);
		orders.setPayStatus(Orders.UN_PAID);
		orders.setOrderTime(LocalDateTime.now());
		// 插入数据
		orderMapper.submitOrder(orders);
		// 插入详情
		List<OrderDetail> orderDetailList = new ArrayList<>();
		for (ShoppingCart item : cart) {
			OrderDetail orderDetail = new OrderDetail();
			BeanUtils.copyProperties(item, orderDetail);
			orderDetail.setOrderId(orders.getId());
			orderDetailList.add(orderDetail);
		}
		orderDetailMapper.submitOrderDetail(orderDetailList);
		// 清空购物车
		shoppingCartMapper.deleteCart(BaseContext.getCurrentId());
		// 返回数据
		return OrderSubmitVO.builder().id(orders.getId()).orderAmount(orders.getAmount()).orderNumber(orders.getNumber()).orderTime(orders.getOrderTime()).build();
	}
	
	
	/**
	 * 订单支付
	 *
	 * @param ordersPaymentDTO
	 * @return
	 */
	@Override
	public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
//		// 当前登录用户id
//		User user = userMapper.getUserId(BaseContext.getCurrentId());
//		//调用微信支付接口，生成预支付交易单

//		JSONObject jsonObject = weChatPayUtil.pay(
//			ordersPaymentDTO.getOrderNumber(), //商户订单号
//			new BigDecimal(0.01), //支付金额，单位 元
//			"苍穹外卖订单", //商品描述
//			user.getOpenid() //微信用户的openid
//		);
		
		
		// 生成空jsonObject
		JSONObject jsonObject = new JSONObject();
		if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
			throw new OrderBusinessException("该订单已支付");
		}
		OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
		vo.setPackageStr(jsonObject.getString("package"));
		return vo;
		
	}
	
	/**
	 * 支付成功，修改订单状态
	 *
	 * @param orderNumber
	 */
	@Override
	public void paySuccess(String orderNumber) {
		
		// 根据订单号查询订单
		Orders order = orderMapper.getByNumber(orderNumber);
		
		// 根据订单id更新订单的状态、支付方式、支付状态、结账时间
		Orders orders = Orders.builder()
				.id(order.getId())
				.status(Orders.TO_BE_CONFIRMED)
				.payStatus(Orders.PAID)
				.checkoutTime(LocalDateTime.now())
				.build();
		
		orderMapper.updateOrder(orders);
		// 推送消息
		Map<String, Object> map = new HashMap<>();
		map.put("type", 1);
		map.put("orderId", order.getId());
		map.put("content", "订单号：" + orderNumber);
		webSocketServer.sendToAllClient(JSON.toJSONString(map));
	}
	
	/**
	 * 查询订单列表
	 *
	 * @param ordersPageQueryDTO
	 * @return
	 */
	@Override
	public PageResult getOrderList(OrdersPageQueryDTO ordersPageQueryDTO) {
		// 设置分页
		PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
		ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
		// 分页条件查询
		Page<Orders> page = orderMapper.getOrderList(ordersPageQueryDTO);
		List<OrderVO> orderVOList = new ArrayList<>();
		if (page != null && page.getTotal() > 0) {
			for (Orders orders : page) {
				OrderVO orderVO = new OrderVO();
				BeanUtils.copyProperties(orders, orderVO);
				orderVO.setOrderDetailList(orderDetailMapper.getOrderId(orders.getId()));
				orderVOList.add(orderVO);
			}
			
		}
		return new PageResult(page.getTotal(), orderVOList);
	}
	
	/**
	 * 再来一单
	 *
	 * @param id
	 */
	@Override
	public void againOrder(Long id) {
		// 根据订单id查询当前订单详情
		List<OrderDetail> orderDetailList = orderDetailMapper.getOrderId(id);
		
		// 将订单详情对象转换为购物车对象
		List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(e -> {
			ShoppingCart shoppingCart = new ShoppingCart();
			// 将原订单详情里面的菜品信息重新复制到购物车对象中
			BeanUtils.copyProperties(e, shoppingCart, "id");
			shoppingCart.setUserId(BaseContext.getCurrentId());
			shoppingCart.setCreateTime(LocalDateTime.now());
			return shoppingCart;
		}).collect(Collectors.toList());
		
		// 将购物车对象批量添加到数据库
		shoppingCartMapper.addBatch(shoppingCartList);
	}
	
	/**
	 * 催单
	 *
	 * @param id
	 */
	@Override
	public void getRemindOrder(Long id) {
		Orders order = orderMapper.getOrder(id);
		if (order == null) {
			throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
		}
		// 推送消息
		Map<String, Object> map = new HashMap<>();
		map.put("type", 2);
		map.put("orderId", id);
		map.put("content", "订单号：" + order.getNumber());
		webSocketServer.sendToAllClient(JSON.toJSONString(map));
	}
	
	/**
	 * 取消订单
	 *
	 * @param id
	 */
	@Override
	public void cancelOrder(Long id) throws Exception {
		// 根据id查询订单
		Orders order = orderMapper.getOrder(id);
		
		// 校验订单是否存在
		if (order == null) {
			throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
		}
		//订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
		if (order.getStatus() > 2) {
			throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
		}
		Orders orders = new Orders();
		orders.setId(order.getId());
		// 订单处于待接单状态下取消，需要进行退款
		if (order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
//			//调用微信支付退款接口
//			weChatPayUtil.refund(
//				order.getNumber(), //商户订单号
//				order.getNumber(), //商户退款单号
//				new BigDecimal(0.01),//退款金额，单位 元
//				new BigDecimal(0.01));//原订单金额
			//支付状态修改为 退款
			orders.setPayStatus(Orders.REFUND);
		}
		// 更新订单状态、取消原因、取消时间
		orders.setStatus(Orders.CANCELLED);
		orders.setCancelReason("用户取消订单");
		orders.setCancelTime(LocalDateTime.now());
		orderMapper.updateOrder(orders);
	}
	
	/**
	 * 管理取消订单
	 *
	 * @param ordersCancelDTO
	 */
	@Override
	public void cancelOrders(OrdersCancelDTO ordersCancelDTO) throws Exception {
		// 根据id查询订单
//		Orders order = orderMapper.getOrder(ordersCancelDTO.getId());
//		if (order.getPayStatus() == 1) {
		//用户已支付，需要退款
//			String refund = weChatPayUtil.refund(
//				order.getNumber(),
//				order.getNumber(),
//				new BigDecimal(0.01),
//				new BigDecimal(0.01));
//			log.info("申请退款：{}", refund);
//		}
		// 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
		orderMapper.updateOrder(Orders.builder().id(ordersCancelDTO.getId()).status(Orders.CANCELLED).cancelReason(ordersCancelDTO.getCancelReason()).cancelTime(LocalDateTime.now()).build());
	}
	
	/**
	 * 各个状态的订单数量统计
	 *
	 * @return
	 */
	@Override
	public OrderStatisticsVO getOrderStatistics() {
		// 根据状态，查询订单数量
		return OrderStatisticsVO.builder().toBeConfirmed(orderMapper.countStatus(Orders.TO_BE_CONFIRMED)).confirmed(orderMapper.countStatus(Orders.CONFIRMED)).deliveryInProgress(orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS)).build();
	}
	
	/**
	 * 订单完成
	 *
	 * @param id
	 */
	@Override
	public void completeOrder(Long id) {
		Orders order = orderMapper.getOrder(id);
		// 校验订单是否存在，并且状态为4
		if (order == null || !order.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
			throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
		}
		orderMapper.updateOrder(Orders.builder().id(order.getId()).status(Orders.COMPLETED).deliveryTime(LocalDateTime.now()).build());
	}
	
	/**
	 * 拒单
	 *
	 * @param ordersRejectionDTO
	 */
	@Override
	public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
		// 根据id查询订单
		Orders order = orderMapper.getOrder(ordersRejectionDTO.getId());
		// 订单只有存在且状态为2（待接单）才可以拒单
		if (order == null || !order.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
			throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
		}
//		if (order.getPayStatus().equals(Orders.PAID)) {
//			//用户已支付，需要退款
//			String refund = weChatPayUtil.refund(
//				order.getNumber(),
//				order.getNumber(),
//				new BigDecimal(0.01),
//				new BigDecimal(0.01));
//			log.info("申请退款：{}", refund);
//		}
		
		// 拒单需要退款，根据订单id更新订单状态、拒单原因、取消时间
		orderMapper.updateOrder(Orders.builder().id(order.getId()).status(Orders.COMPLETED).rejectionReason(ordersRejectionDTO.getRejectionReason()).cancelTime(LocalDateTime.now()).build());
	}
	
	/**
	 * 接单
	 *
	 * @param ordersConfirmDTO
	 */
	@Override
	public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
		orderMapper.updateOrder(Orders.builder().id(ordersConfirmDTO.getId()).status(Orders.CONFIRMED).build());
	}
	
	/**
	 * 派送订单
	 *
	 * @param id
	 */
	@Override
	public void deliveryOrder(Long id) {
		// 根据id查询订单
		Orders order = orderMapper.getOrder(id);
		// 校验订单是否存在，并且状态为3
		if (order == null || !order.getStatus().equals(Orders.CONFIRMED)) {
			throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
		}
		orderMapper.updateOrder(Orders.builder().id(order.getId()).status(Orders.DELIVERY_IN_PROGRESS).build());
	}
	
	/**
	 * 订单搜索
	 *
	 * @param ordersPageQueryDTO
	 * @return
	 */
	@Override
	public PageResult conditionSearchOrder(OrdersPageQueryDTO ordersPageQueryDTO) {
		PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
		Page<Orders> page = orderMapper.getOrderList(ordersPageQueryDTO);
		// 部分订单状态，需要额外返回订单菜品信息，将Orders转化为OrderVO
		return new PageResult(page.getTotal(), getOrderVOList(page));
	}
	
	private List<OrderVO> getOrderVOList(Page<Orders> page) {
		// 需要返回订单菜品信息，自定义OrderVO响应结果
		List<OrderVO> orderVOList = new ArrayList<>();
		List<Orders> ordersList = page.getResult();
		if (!CollectionUtils.isEmpty(ordersList)) {
			for (Orders orders : ordersList) {
				// 将共同字段复制到OrderVO
				OrderVO orderVO = new OrderVO();
				BeanUtils.copyProperties(orders, orderVO);
				// 将订单菜品信息封装到orderVO中，并添加到orderVOList
				orderVO.setOrderDishes(getOrderDishesStr(orders));
				orderVOList.add(orderVO);
			}
		}
		return orderVOList;
	}
	
	/**
	 * 根据订单id获取菜品信息字符串
	 *
	 * @param orders
	 * @return
	 */
	private String getOrderDishesStr(Orders orders) {
		// 查询订单菜品详情信息（订单中的菜品和数量）
		List<OrderDetail> orderDetailList = orderDetailMapper.getOrderId(orders.getId());
		// 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3；）
		// 将该订单对应的所有菜品信息拼接在一起
		return orderDetailList.stream().map(e -> e.getName() + "*" + e.getNumber() + ";").collect(Collectors.joining(""));
	}
	
	
	/**
	 * 检查客户的收货地址是否超出配送范围
	 *
	 * @param address
	 */
	private void checkOutOfRange(String address) {
		Map map = new HashMap();
		map.put("address", shopAddress);
		map.put("output", "json");
		map.put("ak", ak);
		
		//获取店铺的经纬度坐标
		String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
		
		JSONObject jsonObject = JSON.parseObject(shopCoordinate);
		if (!jsonObject.getString("status").equals("0")) {
			throw new OrderBusinessException("店铺地址解析失败");
		}
		
		//数据解析
		JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
		//店铺经纬度坐标
		String shopLngLat = location.getString("lat") + "," + location.getString("lng");
		
		map.put("address", address);
		//获取用户收货地址的经纬度坐标
		String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
		
		jsonObject = JSON.parseObject(userCoordinate);
		if (!jsonObject.getString("status").equals("0")) {
			throw new OrderBusinessException("收货地址解析失败");
		}
		
		//数据解析
		location = jsonObject.getJSONObject("result").getJSONObject("location");
		//用户收货地址经纬度坐标
		String userLngLat = location.getString("lat") + "," + location.getString("lng");
		
		map.put("origin", shopLngLat);
		map.put("destination", userLngLat);
		map.put("steps_info", "0");
		
		//路线规划
		String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);
		
		jsonObject = JSON.parseObject(json);
		if (!jsonObject.getString("status").equals("0")) {
			throw new OrderBusinessException("配送路线规划失败");
		}
		
		//数据解析
		JSONArray jsonArray = (JSONArray) jsonObject.getJSONObject("result").get("routes");
		Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
		
		if (distance > 50000) {
			//配送距离超过5000米
			throw new OrderBusinessException("超出配送范围");
		}
	}
}
